import { useEffect, useState, useRef } from "react";
import "./App.css";
// import * as Colyseus from "colyseus.js";
// import clientData from "./clientData.js";


const App = () => {

  const [loading, setLoading] = useState(false);
  const iframeRef = useRef(null);

  /** 发消息给Iframe */
  const sendMsgToIframe = (data) => {
    const iframe_id = document.getElementById("iframe-id");
    iframe_id.contentWindow.postMessage(JSON.stringify(data), "*");
  }

  /** 连接服务器 */
  // const connectServer = () => {
  //   var client = new Colyseus.Client('ws://43.128.170.225:9000'); //worldapi.shiku.com:80   192.168.1.12:2567
  //   client.joinOrCreate("cocos_game_room", { "token": "981d623a5d67f340e915276e32be18d6" }).then(room => {
  //     console.log("room.state>>>", room.state);
  //     console.log(room.sessionId, "joined", room.name);
  //     window.mRoom = room;

  //     room.onMessage("*", (type, message) => {
  //       console.log(client.id, "received on", room.name, message);
  //     });

  //     room.onStateChange((state) => {
  //       console.log('state>>>', state);
  //       sendMsgToIframe(state);
  //     });

  //   }).catch(e => {
  //     console.log("JOIN ERROR", e);
  //   });

  // }

  const iframeOnload = () => {
    setLoading(true);
  };

  //react接受iframe数据
  const receiveMessageFromIframe = (params) => {
    if (params && params.data) {
      console.log("react页收到的iframe信息:", params.data);
      try {
        var data = JSON.parse(params.data)
      } catch (error) {
      }
      // if (data && data.cmd && window.mRoom) {
      //   window.mRoom.send(data.cmd, data.data);
      // }
      if(data && data.eventName === "webLogin"){
        sendMsgToIframe({
          eventName : "webLogin",
          token : "fcd480a5a485c85db40c4bcca1b31d75"
        })
      }

      // if (data && data.cmd) {
      //   switch (data.cmd) {
      //     case clientData.Commands.gameStart:
      //       clientData.onGameStart();
      //       break;
      //     case clientData.Commands.gameEnd:
      //       clientData.onGameEnd(data.data.result);
      //       break;
      //     case clientData.Commands.addScore:
      //       clientData.onAddScore();
      //       break;
      //   }
      //   sendMsgToIframe(clientData.userData)
      // }
    }
  };

  // 我这里是页面一进来就会发送数据但是必须等iframe加载完成才会发送
  useEffect(() => {
    const window = iframeRef.current?.contentWindow; //因为这里可能会是空值
    if (!!window) {
      if (!loading) return;
      // connectServer();
      sendMsgToIframe({
        eventName : "webLogin",
        token : "b600e5e66ba49758fb1f370b7a57e61b"
      })

      // setTimeout(()=>{
      //   console.log("4秒后执行")
      //   sendMsgToIframe({
      //     eventName : "webLogin",
      //     token : "fcd480a5a485c85db40c4bcca1b31d75"
      //   })
      // },4000)
    }
  }, [loading]);

  useEffect(() => {
    //监听message事件
    window.addEventListener("message", receiveMessageFromIframe, false);
  }, [])

  return (
    <div>
      <iframe
        allow="camera;microphone"
        title="iframe-title"
        id="iframe-id"
        ref={iframeRef}
        onLoad={iframeOnload}
        src="https://192.168.1.172:6443/shiku_webgl/index.html?type=1&map=MeetingPrepareScene"
        style={{ width: "100vw",height:"50vw"}}
        sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
      ></iframe>
    </div>
  );
};

export default App;
